package com.quanshu.exchange.ui.gui.message.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.LabelEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpLabelEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/21.
 */

public class FriendLabelListActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.add_member_lable_rel)
    RelativeLayout addMemberLableRel;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private SingleAdapter<TmpLabelEntity> adapter;
    private List<TmpLabelEntity> tmpLabelList = new ArrayList<>();
    private List<UserEntity> friendList;
    private boolean isShowDelete = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_label_list);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        asyncFetchContactsFromServer();
    }

    private void initIntent() {
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<TmpLabelEntity>(this, R.layout.item_friend_label_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<TmpLabelEntity> wrapper, final TmpLabelEntity item, final int position) {
                holder.setText(R.id.label_name, item.getLabelName());
                holder.setText(R.id.label_member_num, "( " + item.getLabelMemberNum() + " )");
                holder.setText(R.id.label_member, item.getLabelMember());
                holder.setOnClickListener(view -> goUpdateLabelActivity(item));

                if (isShowDelete) {
                    holder.setVisibility(R.id.label_delete, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.label_delete, View.GONE);
                }
                RxViewHelper.getInstance().longClicks(holder.getRootView(), aVoid -> {
                    isShowDelete = !isShowDelete;
                    adapter.notifyDataSetChanged();
                });
                holder.getView(R.id.label_delete).setOnClickListener(view -> doRemoveLabel(item, position));
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(addMemberLableRel, aVoid -> goAddLabelActivity());
    }

    private void initData() {

        friendList = UserDao.getInstance().queryForAll();
        if (friendList == null) {
            friendList = new ArrayList<>();
        }
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getFriendLabelList(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<LabelEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<LabelEntity>> response) {
                        formatList(response.getInfo());
                    }
                });
    }

    private void goUpdateLabelActivity(TmpLabelEntity tmpLabelEntity) {
        Intent intent = new Intent(this, UpdateLabelActivity.class);
        intent.putExtra("TmpLabelEntity", tmpLabelEntity);
        startActivity(intent);
    }

    private void goAddLabelActivity() {
        Intent intent = new Intent(this, AddLabelActivity.class);
        startActivity(intent);
    }

    private void doRemoveLabel(TmpLabelEntity labelEntity, int position) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .removeLabel(AppUtils.getSignParams(labelEntity.getLabelId()), labelEntity.getLabelId())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast("删除成功");
                        adapter.getData().remove(position);
                        adapter.notifyItemRemoved(position);
                        adapter.notifyItemRangeChanged(0, adapter.getData().size());
                    }
                });
    }

    private void formatList(List<LabelEntity> labelList) {
        if (labelList == null || labelList.size() < 1) {
            return;
        }
        tmpLabelList.clear();
        TmpLabelEntity tmpLabelEntity;
        for (int i = 0; i < labelList.size(); i++) {
            tmpLabelEntity = new TmpLabelEntity();
            tmpLabelEntity.setLabelId(labelList.get(i).getId());
            tmpLabelEntity.setLabelName(labelList.get(i).getLabel_name());
            int z = 0;
            StringBuffer memberName = new StringBuffer();
            StringBuffer memberId = new StringBuffer();
            for (int j = 0; j < friendList.size(); j++) {
                if (labelList.get(i).getId().equals(friendList.get(j).getLabel_id())) {
                    z += 1;
                    String string = AppUtils.getUserName(friendList.get(j));
                    memberName.append(string);
                    memberId.append(friendList.get(j).getMemberid());
                    memberName.append(",");
                    memberId.append(",");
                }
            }
            tmpLabelEntity.setLabelMemberNum(z);
            tmpLabelEntity.setLabelMember(memberName.toString());
            tmpLabelEntity.setLabelMemberId(memberId.toString());
            tmpLabelList.add(tmpLabelEntity);
        }
        adapter.setData(tmpLabelList);
    }

    private void asyncFetchContactsFromServer() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getFriendList(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<UserEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<UserEntity>> response) {
                        UserDao.getInstance().save(response.getInfo());
                        initData();
                    }
                });
    }
}
